/*
*********************************************************************************************************
*********************************************************************************************************
* File : subprogram.c
* By : Minglie
* Date :
*********************************************************************************************************
*/

#define OS_GLOBALS
#include "main.h"
#include "string.h"
#include "Function.h"
#include "Main_Constant.h"
#include "ucos.h"
#include "task0.h"
#include "key_task1.h"
#include "task2.h"
#include "stdio.h"
#include <stdlib.h>
#include "stdarg.h"
#include "spitringbuff.h"
#include "strtokmethod.h"



unsigned char usartFlagCount=0;

 
 
ADC_HandleTypeDef ADC1_Handler;



//定时器3的 10ms中断函数
TIM_HandleTypeDef htim3;

//串口2
UART_HandleTypeDef huart2;
UART_HandleTypeDef huart1;

void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_ADC1_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_TIM3_Init(void);
uint8_t myUart2ReBuf[1];
uint8_t myUart2TxBuf[100]="";
uint8_t myUart1ReBuf[1];
uint8_t myUart1TxBuf[100]="";
uint16_t ADC_Value[4];


int fputc(int ch, FILE *f)
{
 uint8_t temp[1] = {ch};
 HAL_UART_Transmit(&huart1, temp, 1, 2);
 return ch;
}

char debug_printf_buf[256];
int debug_printf(const char *fmt, ...)
{
	int printed;
	va_list args;
	va_start(args, fmt);
	printed = vsprintf(debug_printf_buf, fmt, args);
	va_end(args);
	HAL_UART_Transmit_IT(&huart1,debug_printf_buf,printed);
	return printed;
}


int uart2_printf(const char *fmt, ...)
{
	int printed;
	va_list args;
	va_start(args, fmt);
	printed = vsprintf(debug_printf_buf, fmt, args);
	va_end(args);
	HAL_UART_Transmit_IT(&huart2,debug_printf_buf,printed);
	return printed;
}



SpitRingBuff_TypeDef ringBuff1 = {0};

uint16_t Get_Adc()   
{
    ADC_ChannelConfTypeDef ADC1_ChanConf;
    ADC1_ChanConf.Channel=5;                                   //通道
    ADC1_ChanConf.Rank=1;                                       //第1个序列，序列1
    ADC1_ChanConf.SamplingTime=ADC_SAMPLETIME_239CYCLES_5;      //采样时间               
    HAL_ADC_ConfigChannel(&ADC1_Handler,&ADC1_ChanConf);        //通道配置
    HAL_ADC_Start(&ADC1_Handler);                               //开启ADC
    HAL_ADC_PollForConversion(&ADC1_Handler,10);                //轮询转换
	  return (uint16_t)HAL_ADC_GetValue(&ADC1_Handler);	        	//返回最近一次ADC1规则组的转换结果
}





void executeModbusMcuCmd() {
	
	
	 
}





void task3()
{
	 WHILE(1){
		 OSTimeDly(1);
		 //spitRingBuffSpitPackHandel(&ringBuff1);
	 }
}


static NodeServerIoTypeDef nsio={0};

void task4()
{
	 WHILE(1){
		 
		  OSTimeDlyMS(500);
		
		 	nsio.i0=	nsio.i0+3.7;
		 	nsio.i1=  nsio.i1+7;
		 
		 if(1){
		 
		   uart2_printf("f(%0.2f,%d,%d,%d)\n",
		   nsio.i0,nsio.i1,
		   nsio.o0,nsio.o1);
		 
		 }
		
		  HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_13); 
	 }
}





void mcu_init(){

	ringBuff1.enableReadLine=1;
	
	ADC_Value[0]=0;
  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init();
	MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_TIM3_Init();
  HAL_NVIC_EnableIRQ(EXTI15_10_IRQn); 
	HAL_TIM_Base_Start_IT(&htim3);   
	HAL_UART_Receive_IT(&huart2,myUart2ReBuf,1);

   MX_ADC1_Init();

	start_task0();
	start_key_task1();
	start_task2();
	OSTaskCreate(task3);
	

	 OSTaskCreate(task4);
   StrtokMethodTypeDef r=	strtokParseMethodStr("ming(771,2)");
	 printf(r.method);
	 printf(r.arg0);
	 printf(r.arg1);
	
}





uint8_t ringBuff1ReadBuffer[50];
uint16_t ringBuff1PackLen;
void mcu_task(){
	WHILE(1){
			if(0==spitRingBuffRead(&ringBuff1,ringBuff1ReadBuffer,&ringBuff1PackLen))
			{	
			
				 printf("\nR:%s\n",ringBuff1ReadBuffer);
			   StrtokMethodTypeDef r=	strtokParseMethodByteArr(ringBuff1ReadBuffer);
				 switch (r.method[0]){
				
					 	 case 'i':{
					        if(r.arg0[0]!='_'){
									   nsio.i0=atoi(r.arg0);
									}
					        if(r.arg1[0]!='_'){
									   nsio.i1=atoi(r.arg1);
									}
						     break;
					 }
					 case 'o':{
						      if(r.arg0[0]!='_'){
									   nsio.o0=atoi(r.arg0);
									}
					        if(r.arg1[0]!='_'){
									   nsio.o1=atoi(r.arg1);
									}
						     break;
					 }
				 }
				
			}
	}
}






/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
  PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV2;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
	
	HAL_InitTick(TICK_INT_PRIORITY);
}






/**
  * @brief TIM3 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM3_Init(void)
{
  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 15999;
  htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim3.Init.Period = 5;
  htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
  if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  huart2.Instance = USART2;
  huart2.Init.BaudRate = 9600;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  __HAL_UART_ENABLE_IT(&huart2, UART_IT_RXNE);
	
	HAL_UART_Receive_IT(&huart2,myUart2ReBuf,1);
	
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }

}

static void MX_USART1_UART_Init(void)
{

    huart1.Instance = USART1;
    huart1.Init.BaudRate = 9600;
    huart1.Init.WordLength = UART_WORDLENGTH_8B;
    huart1.Init.StopBits = UART_STOPBITS_1;
    huart1.Init.Parity = UART_PARITY_NONE;
    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
	
	  __HAL_UART_ENABLE_IT(&huart1, UART_IT_RXNE);
	
	  HAL_UART_Receive_IT(&huart1,myUart1ReBuf,1);
	
	
    if (HAL_UART_Init(&huart1) != HAL_OK)
    {
         Error_Handler();
    }

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
 __HAL_RCC_GPIOB_CLK_ENABLE();
	


  /*Configure GPIO pins : PA5 PA6 PA7 */
  GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_6|GPIO_PIN_7;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
	GPIO_InitStruct.Pin=GPIO_PIN_All;
	HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
	
	GPIO_InitStruct.Pin =GPIO_PIN_6|GPIO_PIN_7;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
 
	GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15;
	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
	
	
			GPIO_InitStruct.Pin =GPIO_PIN_13;
		GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
		HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
	
  /* EXTI interrupt init*/
  HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);

}

/* USER CODE BEGIN 4 */


//外部中断
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	if(GPIO_Pin==GPIO_PIN_13)
	{

		
	}
	
}





/**
  * @brief ADC1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_ADC1_Init(void)
{

  /* USER CODE BEGIN ADC1_Init 0 */

  /* USER CODE END ADC1_Init 0 */

  ADC_ChannelConfTypeDef sConfig = {0};

  /* USER CODE BEGIN ADC1_Init 1 */

  /* USER CODE END ADC1_Init 1 */
  /** Common config 
  */
  ADC1_Handler.Instance = ADC1;
  ADC1_Handler.Init.ScanConvMode = ADC_SCAN_DISABLE;
  ADC1_Handler.Init.ContinuousConvMode = ENABLE;
  ADC1_Handler.Init.DiscontinuousConvMode = DISABLE;
  ADC1_Handler.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  ADC1_Handler.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  ADC1_Handler.Init.NbrOfConversion = 1;
  if (HAL_ADC_Init(&ADC1_Handler) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel 
  */
  sConfig.Channel = ADC_CHANNEL_5;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
  if (HAL_ADC_ConfigChannel(&ADC1_Handler, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC1_Init 2 */

  /* USER CODE END ADC1_Init 2 */

}






//TIM定时器中断服务程序10ms
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{ 

		if(htim==&htim3)
		{
				//HAL_UART_Transmit_IT(&huart2, "123",3);
			//OSTimeTick();
		}
}




 //串口接收中断
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
     
		if(huart==&huart2)
		{	
			  spitRingBuffWriteChar(&ringBuff1,myUart2ReBuf[0]);
			  HAL_UART_Receive_IT(&huart2,myUart2ReBuf,1);
		}
		if(huart==&huart1)
		{	
			  //spitRingBuffWriteChar(myUart2ReBuf[0]);
			  //HAL_UART_Receive_IT(&huart2,myUart2ReBuf,1);
		}
}




/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}




 void HAL_SYSTICK_Callback(void){

  
		OSTimeTick();
	 
		
 
 }




 void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* AdcHandle)
{
   
}




